import pickle
import face_recognition
import numpy as np

class FaceRecognition:
    def __init__(self):
        self.known_face_encodings = []
        self.known_face_names = []

    def add_face(self, res):
        res.start()
        ans = res.query()
        for i in ans:
            codeings = pickle.loads(i[2])
            self.known_face_encodings.append(codeings)
            self.known_face_names.append(i[1])

    def recognize_faces(self, unknown_image_path):
        unknown_image = face_recognition.load_image_file(unknown_image_path)

        face_locations = face_recognition.face_locations(unknown_image)
        face_encodings = face_recognition.face_encodings(unknown_image, face_locations)

        names = []
        for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
            matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding)

            name = "Unknown"
            face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = self.known_face_names[best_match_index]
                names.append(name)

        return names
    